<template>
  <div class="dropzone" @drop="drop($event)" @dragover="dragOver($event)">
    <h2>Languages</h2>
    <div
      v-for="(item, index) in languages"
      :key="item.name"
      class="draggable"
      draggable="true"
      @dragstart="dragStart(index)"
      @dragenter="dragEnter(index)"
      @dragleave="dragLeave"
    >
      {{ item.name }}
    </div>
  </div>
</template>

<script setup lang="ts">
  import { reactive } from 'vue'
  import { delay } from '@/hooks/utils'

  interface Language {
    name: string
  }

  const languages = reactive<Language[]>([
    {
      name: 'typescript'
    },
    {
      name: 'javascript'
    },
    {
      name: 'C++'
    },
    {
      name: 'java'
    },
    {
      name: 'rust'
    },
    {
      name: 'golang'
    }
  ])
  const record = reactive({
    current: -1,
    replace: -1
  })
  // 排序方式
  const reorder = (languages: Language[], current: number, replace: number) => {
    if (current === -1 || replace === -1) {
      return
    }
    const [removedLanguage] = languages.splice(current, 1)
    languages.splice(replace, 0, removedLanguage)
  }
  const dragStart = (index: number) => {
    record.current = index
  }
  const dragEnter = (index: number) => {
    record.replace = index
    console.log('结束')
  }
  // drop 事件在元素或选中的文本被放置在有效的放置目标上时被触发
  const drop = (event: DragEvent) => {
    event.preventDefault()
    reorder(languages, record.current, record.replace)
  }
  // 当元素或者选择的文本被拖拽到一个有效的放置目标上时，触发 dragover 事件（每几百毫秒触发一次）
  const dragOver = async (event: DragEvent) => {
    // await delay(1000)
    console.log(event)

    event.preventDefault()
  }
  const dragLeave = (event: DragEvent) => {
    event.preventDefault()
  }
</script>

<style scoped lang="less">
  .draggable {
    background-color: red;
    width: 200px;
    margin-top: 10px;
    height: 60px;
    line-height: 60px;
  }

  .dropzone {
    background-color: yellow;
  }
</style>
